import React, { useState } from "react";
import { Select } from "@/views/components/PrefixPlaceholder";

import request from "@/utils/request";
import { stringify } from "qs";

// 获取门店（供应商）列表
// export async function getZJFStorePage(params) {
// 	return request(`/blade-goods/zjfstore/list/fuzzyQueryPage?${stringify(params)}`, { method: "GET", loading: true });
// }
// 获取档口号
export async function getZJFStorePage(params) {
	return request(`/zjf-wms/store/findDaifaStorePage`, {
		method: "POST",
		loading: false,
		data: params
	});
}
// 档口号模糊查询
export async function getZJFshopCodePage(params) {
	return request(`/zjf-wms/store/shopCodeList?${stringify(params)}`, {});
}
export async function queryAreaCode(params) {
	return request(`/zjf-wms/storecodesort/selectListByName?${stringify(params)}`);
}
// 获取门店（供应商）列表
export async function getZJFStoreFuzzyQueryPage(params) {
	params.state = 1;
	return request(`/blade-goods/zjfstore/list/fuzzyQueryPage?${stringify(params)}`);
}

/**
 * type:   shopCode  档口编码搜索 , storeName 供应商名称模糊搜索
 */
export default ({ type = "storeName", valueKey = "storeId", onChange, origin, value, mode, apiKey, ...props }) => {
	const API_MAP = {
		getZJFStorePage,
		getZJFshopCodePage,
		queryAreaCode,
		getZJFStoreFuzzyQueryPage
	};
	let timeout;
	let currentValue;
	const isStoreName = type == "storeName";

	const valueFn = item => item[valueKey];
	const labelFn = item => (isStoreName ? item["storeName"] : `${item["storeName"]} ${item["shopCode"]}`);

	const fetch = (value, callback) => {
		if (timeout) {
			clearTimeout(timeout);
			timeout = null;
		}
		currentValue = value;
		const fake = () => {
			if (!apiKey) {
				apiKey = isStoreName ? "getZJFStoreFuzzyQueryPage" : "getZJFStorePage";
			}
			const API = API_MAP[apiKey];

			const API_DATA = apiKey == "getZJFshopCodePage" ? { shopCode: value } : { [type]: value };
			API(API_DATA).then(res => {
				if (currentValue === value) {
					const { data } = res;
					const arr = data.records && Array.isArray(data.records) ? data.records : Array.isArray(data) ? data : [];
					const records = arr.map(item => ({
						value: typeof item === "string" ? item : valueFn(item),
						text: typeof item === "string" ? item : labelFn(item)
					}));
					callback(records);
				}
			});
		};
		if (value) {
			timeout = setTimeout(fake, 300);
		} else {
			callback([]);
		}
	};

	const [data, setData] = useState([]);
	const handleSearch = newValue => {
		fetch(newValue, setData);
	};
	const handleChange = newValue => {
		onChange(newValue);
	};
  
	return (
		<Select
			showSearch
            allowClear
			value={value}
			origin={origin}
			defaultActiveFirstOption={false}
			suffixIcon={null}
			mode={mode}
			filterOption={false}
			onSearch={handleSearch}
			onChange={handleChange}
			notFoundContent={null}
			options={(data || []).map(d => ({
				value: d.value,
				label: d.text
			}))}
			{...props}
		/>
	);
};
